import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Category from '../views/Category'
import Shopcart from '../views/Shopcart'
import My from '../views/My'
import GoodsList from '../views/GoodsList'
import Goods from '../views/Goods'
import Themes from '../views/Themes'
import CategoryList from '../views/CategoryList'
import Login from '../views/Login'
import { Toast } from 'vant'
Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/home', meta: { title: '首页' } },
  {
    path: '/home',
    name: 'home',
    meta: { title: '首页' },
    component: Home
  },
  {
    path: '/category',
    name: 'category',
    meta: { title: '分类' },
    component: Category
  },
  {
    path: '/shopcart',
    name: 'shopcart',
    meta: { title: '购物车' },
    component: Shopcart
  },
  {
    path: '/my',
    name: 'user',
    meta: { title: '我的' },
    component: My
  },
  {
    path: '/goods', component: GoodsList, name: 'GoodsList', meta: {
      title: '商品列表'
    }, props: true
  },
  {
    path: '/goodsInfo/:id', component: Goods, name: 'Goods', meta: {
      title: '商品详细'
    }, props: true
  },
  {
    path: '/home/themes', component: Themes, name: 'Themes', meta: {
      title: '专题详情'
    }, props: true
  },
  {
    path: '/category/categorylist', component: CategoryList, name: 'CategoryList', meta: {
      title: '分类商品'
    }, props: true
  },
  {
    path: '/user/login', component: Login, meta: {
      title: '登录'
    },
  },
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  let needTokenPage = ['buy', 'shopcart', 'order', 'my', 'adress']
  if (!needTokenPage.includes(to.name)) return next();

  const token = localStorage.getItem('Authorization')
  if (!token) {
    Toast.fail('请先登录')
    return next('/user/login')
  }
  next()
})

export default router
